package com.czwx.bee.business.manager.modular.sys.controller;

import com.czwx.bee.base.common.dto.ResponseDto;
import com.czwx.bee.base.common.exception.BizExceptionEnum;
import com.czwx.bee.base.web.support.HttpKit;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Map;

/**
 *   /error 请求自定义~
 */

@RestController
@ApiIgnore
public class TokenErrorController extends BasicErrorController {


    public TokenErrorController(){
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }

    private static final String PATH = "/error";

    @RequestMapping(
            produces = {"text/html"}
    )
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = this.getStatus(request);
        Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());
        if((Integer)model.get("status")==403&&model.get("error").equals("Forbidden")){
            HttpKit.responseJson(response,new ResponseDto(BizExceptionEnum.LOGIN_TOKEN_FAILED));
        }
        ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
        return modelAndView == null ? new ModelAndView("error", model) : modelAndView;
    }

    @RequestMapping
    @ResponseBody
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = this.getStatus(request);
        if((Integer)body.get("status")==403&&body.get("error").equals("Forbidden")){
            body.clear();
            body.put("code",BizExceptionEnum.LOGIN_TOKEN_FAILED.getCode());
            body.put("mesg",BizExceptionEnum.LOGIN_TOKEN_FAILED.getMessage());
            status=HttpStatus.OK;
        }
        return new ResponseEntity(body, status);
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}